package com.peanut.baby.mvp.bbs.list;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.MyViewPagerAdapter;
import com.peanut.baby.model.Ad;
import com.peanut.baby.model.BBSMoment;
import com.peanut.baby.mvp.bbs.BBSBaseActivity;
import com.peanut.baby.mvp.bbs.BBSRecycleListAdapter;
import com.peanut.baby.mvp.bbs.publish.BBSPublishActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.widget.TitleLayout;
import com.peanut.devlibrary.widget.pullrecycle.PullRecyclerView;
import com.peanut.devlibrary.widget.pullrecycle.layoutmanager.XLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/8/23.
 */

public class BBSListActivity extends BBSBaseActivity implements BBSListContract.View,
        TitleLayout.OnTitleClickListener,
        PullRecyclerView.OnRecyclerRefreshListener ,ViewPager.OnPageChangeListener{

    public static final int TYPE_USER_MOMENTS = 1;
    public static final int TYPE_SELF_CIRCLE = 2;
    public static final int TYPE_HOT_CIRCLE = 3;    //头条推荐
    public static final int TYPE_ALL_CIRCLE = 4;    //滚动更新


    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.bbs_list)
    PullRecyclerView bbsList;
    @BindView(R.id.banner_viewpager)
    ViewPager bannerViewpager;
    @BindView(R.id.banner_radiogroup)
    RadioGroup bannerRadiogroup;
    @BindView(R.id.banner_frame)
    FrameLayout bannerFrame;
    private String userId = "";
    private int type = TYPE_USER_MOMENTS;
    private List<BBSMoment> moments;
    private BBSRecycleListAdapter adapter;
    private int pageNo = 1;
    private int pageSize = 10;
    private BBSListPresenter presenter;

    protected MyViewPagerAdapter mAdAdapter;                      //banner适配器
    protected List<View> mAdViews;
    private Runnable scrollRunnable;
    private boolean resumed = false;
    private Handler handler = new Handler();

    public static void start(Context ctx, String userId) {
        ctx.startActivity(new Intent(ctx, BBSListActivity.class).putExtra("userId", userId).putExtra("type", TYPE_USER_MOMENTS));
    }

    public static void start(Context ctx, int type) {
        ctx.startActivity(new Intent(ctx, BBSListActivity.class).putExtra("type", type));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbs_list);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", TYPE_USER_MOMENTS);
        userId = getIntent().getStringExtra("userId");
        presenter = new BBSListPresenter(this, this);
        fixBannerSize();
        initView();
    }

    private void initView() {
        String titleString = "内容";
        if (type == TYPE_SELF_CIRCLE) {
            titleString = "我的圈子";
        } else if (type == TYPE_HOT_CIRCLE) {
            titleString = "滚动更新";
        } else if (type == TYPE_ALL_CIRCLE) {
            titleString = "头条推荐";
        } else if (InitManager.getInstance().getUserId().equals(userId)) {
            titleString = "我的内容";
        }
        title.setTitle(titleString);
        title.setOnTitleClickedListener(this);


        if (type == TYPE_SELF_CIRCLE) {
            title.setTitleRightText("发布内容");
            title.setTitleRightVisibility(true);
            title.setTitleRightTextColor(getResources().getColor(R.color.colorPrimary));
        }


        bbsList.enableLoadMore(true);
        bbsList.enablePullRefresh(true);
        bbsList.setOnRecyclerRefreshListener(this);

        moments = new ArrayList<>();
        adapter = new BBSRecycleListAdapter(this, moments);
        bbsList.setLayoutManager(new XLinearLayoutManager(this));
        bbsList.setAdapter(adapter);
        scrollRunnable = new Runnable() {
            @Override
            public void run() {
                if (mAdAdapter != null && mAdAdapter.getCount() > 0) {
                    int currentIndex = bannerViewpager.getCurrentItem();
                    int pos = currentIndex + 1;
                    if (pos > mAdAdapter.getCount() - 1) {
                        pos = 0;
                    }

                    bannerViewpager.setCurrentItem(pos);
                }
                if (resumed) {
                    handler.postDelayed(scrollRunnable, 3000);
                }
            }
        };
        presenter.getBanner(type);

        bbsList.postRefreshing();
    }

    @Override
    protected void onResume() {
        super.onResume();
        resumed = true;
        handler.postDelayed(scrollRunnable, 3000);

    }

    @Override
    protected void onPause() {
        super.onPause();
        resumed = false;
        handler.removeCallbacks(scrollRunnable);
    }

    @Override
    public void onMomentsGet(List<BBSMoment> _moments) {
        stopRefreshOrLoading();

        if (pageNo == 1) {
            moments.clear();
        }
        if (_moments != null && !_moments.isEmpty()) {
            moments.addAll(_moments);
        }
        adapter.notifyDataSetChanged();
        bbsList.enableLoadMore(_moments != null && _moments.size() >= pageSize);
    }

    @Override
    public void onGetMomentsFailed(String reason) {
        stopRefreshOrLoading();
        bbsList.enableLoadMore(false);
        showToast(reason);
    }

    private void fixBannerSize(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bannerFrame.getLayoutParams();
        params.height = InitManager.getInstance().getScreenWidth() * 3 / 5;
        bannerFrame.setLayoutParams(params);
    }

    @Override
    public void onBannerGet(boolean success, List<Ad> ads, String failReason) {
        initBanners(ads);
    }

    private void fakeHideBanner(){
        //
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bannerFrame.getLayoutParams();
        params.height = 1;
        bannerFrame.setLayoutParams(params);
    }

    private void initBanners(final List<Ad> objs) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (objs == null || objs.isEmpty()) {
                    fakeHideBanner();
                    return;
                }

                if (mAdViews == null) {
                    mAdViews = new ArrayList<View>();
                }
                mAdViews.clear();
                bannerRadiogroup.removeAllViews();
                int size = objs.size();
                int rightMargin = getResources().getDimensionPixelSize(R.dimen.ad_radio_size);
                for (int i = 0; i < size; i++) {
                    final Ad ad = objs.get(i);
                    final View adView = getLayoutInflater().inflate(R.layout.layout_ad, null);
                    final ImageView img = (ImageView) adView.findViewById(R.id.ad_image);

                    ImageLoader.getInstance().loadImageView(BBSListActivity.this, ad.imgUrl, img);


                    mAdViews.add(adView);

                    adView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            WebViewActivity.start(BBSListActivity.this, ad.htmlUrl, ad.name,ad.imgUrl);
                        }
                    });

                    RadioButton radioButton = new RadioButton(BBSListActivity.this);
                    radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
                    try {
                        radioButton.setBackgroundDrawable(BBSListActivity.this.getResources().getDrawable(R.drawable.selector_ad_radiobutton));
                    } catch (Resources.NotFoundException e) {
                        e.printStackTrace();
                    }
                    RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(rightMargin, rightMargin);
                    if (i != (size - 1)) {
                        params.rightMargin = rightMargin;
                    }
                    bannerRadiogroup.addView(radioButton, params);


                }
                ((RadioButton) bannerRadiogroup.getChildAt(0)).setChecked(true);
                mAdAdapter = new MyViewPagerAdapter(mAdViews);
                bannerViewpager.setAdapter(mAdAdapter);
                bannerViewpager.setOnPageChangeListener(BBSListActivity.this);

            }
        });

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {
        BBSPublishActivity.start(this);
    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onPullRefresh() {
        pageNo = 1;
        if (type == TYPE_USER_MOMENTS) {
            presenter.getUserMoments(userId, pageNo, pageSize);
        } else if (type == TYPE_SELF_CIRCLE) {
            presenter.getCircleMoments(pageNo, pageSize);
        } else if (type == TYPE_HOT_CIRCLE) {
            presenter.getAllMoments(pageNo, pageSize);
        } else if (type == TYPE_ALL_CIRCLE) {
            presenter.getHotMoments(pageNo, pageSize);
        } else {
            stopRefreshOrLoading();
        }

    }

    @Override
    public void onLoadMore() {
        pageNo++;
        if (type == TYPE_USER_MOMENTS) {
            presenter.getUserMoments(userId, pageNo, pageSize);
        } else if (type == TYPE_SELF_CIRCLE) {
            presenter.getCircleMoments(pageNo, pageSize);
        } else if (type == TYPE_HOT_CIRCLE) {
            presenter.getAllMoments(pageNo, pageSize);
        } else if (type == TYPE_ALL_CIRCLE) {
            presenter.getHotMoments(pageNo, pageSize);
        } else {
            stopRefreshOrLoading();
        }
    }

    private void stopRefreshOrLoading() {
        bbsList.stopRefresh();
        bbsList.stopLoadMore();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        ((RadioButton) bannerRadiogroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
